package com.example.ckycode.servlet;

import com.example.skycode.bean.NewsBean;
import com.example.skycode.dao.NewsDao;

import com.example.skycode.bean.NoticeBean;
import com.example.skycode.dao.NoticeDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/notice.jsp")
@WebServlet(value = "/notice.jsp")
public class NoticeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // todo 获取分页页码参数
        // 1.获取新闻信息
        NewsDao newsDao = new NewsDao();
        List<NewsBean> news = null;
        try {
            news = newsDao.getList();
        } catch (SQLException e) {
            throw new RuntimeException(e);
            protected void doGet (HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
                String p = req.getParameter("page");//获取用户传递来的页码
                int page = 1;
                if (p != null && p.equals("")) {
                    page = Integer.parseInt(p);//字符串转整数
                }//
                // 获取新闻信息
                NoticeDao noticeDao = new NoticeDao();
                List<NoticeBean> notice = noticeDao.getList();
                int totalCount, curPage, totalPage, upPage, downPage;
                totalCount = noticeDao.count();//总条数
                curPage = page;//用户传递进来的页码
                if (totalCount % 10 == 0) {
                    totalPage = totalCount / 10;
                } else {
                    totalPage = totalCount / 10 + 1;//计算总页数
                }//
                //上一页 当前页数减去1
                if (curPage == 1) {
                    upPage = 1;
                } else {
                    upPage = curPage - 1;
                }
                if (curPage == totalPage) {
                    downPage = totalPage;
                } else {
                    downPage = curPage + 1;
                }
                // 2.传递新闻信息给前端页面
                req.setAttribute("news", news);
                // 3.加载显示前端页面
                req.getRequestDispatcher("news.jsp").forward(req, resp);
                req.setAttribute("totalCount", totalCount);
                req.setAttribute("curPage", curPage);
                req.setAttribute("totalPage", totalPage);
                req.setAttribute("upPage", upPage);
                req.setAttribute("downPage", downPage);
                // 传递新闻信息给前端页面
                req.setAttribute("notice", notice);
                // 加载显示前端页面
                req.getRequestDispatcher("WEB-INF/notice.jsp").forward(req, resp);

            }
        }
    }
}